package com.zlzlib.librxoknet.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by zlz on 2019/8/23.
 */
public class ReqUtil {

    /**
     * 获得上传 的实体
     *
     * @param key
     * @param value
     * @return
     */
    public static MultipartBody.Part getStringMultipartBody(String key, String value) {
        return MultipartBody.Part.createFormData(key, value);
    }

    /**
     * 获得上传文件的实体
     *
     * @param file
     * @return
     */
    public static MultipartBody.Part getFileMultipartBody(File file) {
        return getFileMultipartBody(file, file.getName(), file.getName());
    }

    public static MultipartBody.Part getFileMultipartBody(File file, String type, String name) {
        return MultipartBody.Part.createFormData(type, name, getFileRequestBody(file));
    }

    public static RequestBody getFileRequestBody(File file) {
        return getFileRequestBody(file, file.getName());
    }

    public static RequestBody getFileRequestBody(File file, String typeName) {
        return RequestBody.create(file, MediaType.parse(guessMimeType(typeName)));
    }

    private static String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = null;
        try {
            contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    /**
     * 获得一个请求体
     *
     * @param hashMap
     * @return
     */
    public RequestBody getRequestBody(HashMap<String, String> hashMap) {
        StringBuffer data = new StringBuffer();
        if (hashMap != null && hashMap.size() > 0) {
            Iterator iterator = hashMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                data.append(key).append("=").append(val).append("&");
            }
        }
        String jso = data.substring(0, data.length() - 1);
        RequestBody requestBody = RequestBody.create(jso, MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"));
        return requestBody;
    }

}
